package tt.dz.appserver.service.business.imp;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.avro.AvroRemoteException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import tt.dz.appserver.dao.ext.UserAuthDao;
import tt.dz.appserver.dao.ext.UserInfoDao;
import tt.dz.appserver.entity.model.user.UserInfo;
import tt.dz.appserver.entity.vo.user.UserDetailVo;
import tt.dz.appserver.service.avro.client.main.MSRPCService;
import tt.dz.appserver.service.business.UserInfoService;
import tt.dz.appserver.util.CodeUtils;
import tt.dz.appserver.util.Constants;
import tt.dz.appserver.util.ConverUtil;
import tt.dz.appserver.util.dzcode.MainServerCode;
import tt.dz.appserver.util.encoding.EncodingUtils;
import tt.dz.appserver.util.enums.MainOpResult;
import tt.dz.appserver.util.enums.MainServerLoginType;
import tt.dz.appserver.util.enums.Response;
import tt.dz.appserver.util.enums.Sex;
import tt.dz.appserver.util.enums.UserType;
import tt.dz.appserver.util.enums.Valid;
import tt.dz.appserver.util.enums.setPwdFlag;
import tt.dz.appserver.util.enums.userIsExists;
import tt.dz.appserver.util.http.HttpUtils;
import tt.dz.appserver.util.json.JsonUtils;
import tt.dz.base.authentication.entity.LoginParam;
import tt.dz.base.authentication.entity.RPCLoginRes;
import tt.dz.base.authentication.entity.RedisUser;
import tt.dz.base.authentication.service.AuthenService;
import tt.dz.base.common.entity.ApiResult;

/**
 * 用户业务实现类
 * 
 * @author Administrator
 *
 */
public class UserInfoServiceImpl implements UserInfoService {

	private final static Logger LOG = Logger.getLogger("[用户业务接口]:");

	/** 主服务器访问接口 */
	@Resource(name = "mainMessageProtocolRequestor")
	private MSRPCService msrpcService;

	@Resource
	private UserAuthDao userAuthDao;

	/** 用户扩展信息 */
	@Resource
	private UserInfoDao userInfoDao;

	/** baseplatform 授权业务接口 */
	@Resource
	private AuthenService authService;

	@Override
	public JSONObject register(String mobileNo, String password, String latitude, String longitude, String addrdetail,
			String areaCode) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", mobileNo);
		params.put("password", password);
		params.put("channel", Constants.systemCode);// 渠道号
		params.put("merchantCode", Constants.merchantCode);// 所属运营商编码
		params.put("latitude", latitude);
		params.put("longitude", longitude);
		params.put("adddetail", addrdetail);
		params.put("areaCode", areaCode);
		// 调用注册接口
		String resultJsonString = msrpcService.regist(JSON.toJSONString(params)).toString();

		LOG.info("MS注册【 " + mobileNo + " 】号码,返回:" + resultJsonString);

		// 将返回的字符转换成json
		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);

		// 成功
		if (opResult == MainOpResult.SUCCESS.getCode()) {

			String userId = mainServerResult.getString("userId");
			String token = mainServerResult.getString("tocken");

			// 用户信息
			UserInfo userInfo = new UserInfo();
			userInfo.setUser_id(userId);
			userInfo.setTelephone(mobileNo);
			userInfo.setLatitude(Float.parseFloat(latitude));
			userInfo.setLongitude(Float.parseFloat(longitude));
			userInfo.setAddress(addrdetail);
			userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
			userInfo.setRegister_time(new Date());
			userInfo.setSex(Sex.MAN.getValue());
			userInfo.setStricted_flag(0);
			userInfo.setKey_char(EncodingUtils.getRandomString(15));
			userInfo.setValid_flag(Valid.YES.getValue());
			userInfo.setAreaCode(areaCode);
			userInfo.setSysCode(Constants.merchantCode);
			// 保存用户信息
			userInfoDao.save(userInfo);

			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(mobileNo);
			userDetailVo.setUserType(UserType.ENTERPRISE.getCode());// 个人用户
			if (userInfo.getNickname() == null || userInfo.getNickname().isEmpty()) {
				userDetailVo.setNickName(mobileNo.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
			} else {
				userDetailVo.setNickName(userInfo.getNickname());
			}

			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());

		} else {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response respond = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject.put("code", respond.getCode());
			resultJsonObject.put("msg", respond.getMsg());
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject userLogin(String baseUrl, String phone, String password, String jPushRegId, String source,
			String merchantCode) {

		JSONObject resultJsonObject = new JSONObject();

		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", phone);
		params.put("password", password);
		params.put("loginType", "1");

		// 调用登录
		LoginParam loginParam = new LoginParam();
		loginParam.setPassword(password);
		loginParam.setMobileNo(phone);
		if (source == null || source.isEmpty()) {
			source = Constants.systemCode;
		}
		loginParam.setSysCode(source);
		if (merchantCode == null || merchantCode.isEmpty()) {
			merchantCode = Constants.merchantCode;
		}
		loginParam.setMerchantCode(merchantCode);
		loginParam.setLoginType(MainServerLoginType.password.getValue());
		ApiResult apiResult = authService.login(loginParam);

		// 获取返回值
		Integer status = apiResult.getStatus();
		LOG.info(" loginmobileNo = " + phone + " back result:  status= ===============  " + status);
		// 放入redis成功
		if (status != null && status == 0) {

			RPCLoginRes loginRes = (RPCLoginRes) apiResult.getData();
			String nickName = loginRes.getNickName();
			String userId = loginRes.getUserId();
			String token = apiResult.getToken();
			String userType = loginRes.getUserType();
			String addrDetail = loginRes.getAdddetail();
			String hasPwd = loginRes.getHasPwd().toString();

			UserInfo userInfo = userInfoDao.findUserByUserId(userId);
			// 如果App服务器没有此用户
			if (userInfo == null) {
				// 用户信息
				userInfo = new UserInfo();
				userInfo.setUser_id(userId);
				userInfo.setTelephone(phone);
				userInfo.setRegister_time(new Date());
				userInfo.setStricted_flag(0);
				userInfo.setSet_pwd_flag(Integer.parseInt(hasPwd));
				userInfo.setKey_char(EncodingUtils.getRandomString(15));
				userInfo.setSex(Sex.MAN.getValue());
				userInfo.setNickname(nickName);
				userInfo.setAddress(addrDetail);
				userInfo.setValid_flag(Valid.YES.getValue());
				userInfo.setJpush_id(jPushRegId);
				userInfo.setSysCode(Constants.merchantCode);
				userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
				
				//查询是否存在jpushRegId; 存在全部为空  一般情况会返回一条记录
				List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
				for(UserInfo jpushUser:jpushUsers){
					jpushUser.setJpush_id("");
					//使用这个单条是方便更新缓存
					userInfoDao.update(jpushUser);
				}
				// 保存用户信息
				userInfoDao.save(userInfo);
			} else {
				if(jPushRegId!=null&&(!jPushRegId.equals(""))){   
					
					List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
					for(UserInfo jpushUser:jpushUsers){
						jpushUser.setJpush_id("");
						//使用这个单条是方便更新缓存
						if(jpushUser.getUser_id().equals(userInfo.getUser_id())){
							continue;
						}
						userInfoDao.update(jpushUser);
					}
					
					userInfo.setJpush_id(jPushRegId);
					userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
					userInfoDao.update(userInfo);
				}

			}

			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(phone);
			userDetailVo.setUserType(userType);// 个人用户
			if (userInfo.getNickname() == null || userInfo.getNickname().isEmpty()) {
				userDetailVo.setNickName(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
			} else {
				userDetailVo.setNickName(userInfo.getNickname());
			}
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());
			userDetailVo.setHeadImage(userInfo.getHead_path());

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			LOG.error("login RpcServers is false ");
			Response response = CodeUtils.getCodeByMainServerCode(status.toString());
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject fastLogin(String phone, String verifyCode, String latitude, String longitude, String terminalType,
			String jPushRegId) throws AvroRemoteException {

		JSONObject resultJsonObject = null;
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobileNo", phone);
		params.put("password", verifyCode);
		params.put("loginType", MainServerLoginType.verify_code.getValue());// 验证码登陆
		params.put("latitude", latitude);
		params.put("longitude", longitude);
		params.put("terminalType", terminalType);
		params.put("sysCode", Constants.systemCode);
		params.put("merchantCode", Constants.merchantCode);

		// 调用快捷登录接口
		LoginParam loginParam = new LoginParam();
		loginParam.setPassword(verifyCode);
		loginParam.setMobileNo(phone);
		loginParam.setSysCode(Constants.systemCode);
		loginParam.setMerchantCode(Constants.merchantCode);
		loginParam.setLoginType(MainServerLoginType.verify_code.getValue());
		ApiResult apiResult = authService.login(loginParam);

		Integer status = apiResult.getStatus();
		LOG.info("fastLogin phone=" + phone + "status=" + status);
		// 登录成功
		if (status != null && status == 0) {

			resultJsonObject = JsonUtils.getSuccessJson();

			RPCLoginRes loginRes = (RPCLoginRes) apiResult.getData();

			String nickName = loginRes.getNickName();
			String userId = loginRes.getUserId();
			String token = apiResult.getToken();
			String userType = loginRes.getUserType();
			String addrDetail = loginRes.getAdddetail();
			String hasPwd = loginRes.getHasPwd().toString();

			// 查询app服务器是否含有此用户
			UserInfo userInfo = userInfoDao.findUserByUserId(userId);

			// 如果没有此用户
			if (userInfo == null) {
				// 用户信息
				userInfo = new UserInfo();
				userInfo.setUser_id(userId);
				userInfo.setNickname(nickName);
				userInfo.setTelephone(phone);
				userInfo.setAddress(addrDetail);
				userInfo.setLatitude(Float.parseFloat(latitude));
				userInfo.setLongitude(Float.parseFloat(longitude));
				userInfo.setSet_pwd_flag(Integer.parseInt(hasPwd));
				userInfo.setRegister_time(new Date());
				userInfo.setStricted_flag(0);
				userInfo.setSex(Sex.MAN.getValue());
				userInfo.setKey_char(EncodingUtils.getRandomString(15));
				userInfo.setJpush_id(jPushRegId);
				userInfo.setValid_flag(Valid.YES.getValue());
				userInfo.setSysCode(Constants.merchantCode);
				
				List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
				for(UserInfo jpushUser:jpushUsers){
					jpushUser.setJpush_id("");
					//使用这个单条是方便更新缓存
					userInfoDao.update(jpushUser);
				}
				
				// 保存用户信息
				userInfoDao.save(userInfo);
			} else {
				if(jPushRegId!=null&&(!jPushRegId.equals(""))){
					
					List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
					for(UserInfo jpushUser:jpushUsers){
						jpushUser.setJpush_id("");
						//使用这个单条是方便更新缓存
						if(jpushUser.getUser_id().equals(userInfo.getUser_id())){
							continue;
						}
						userInfoDao.update(jpushUser);
					}
					
					userInfo.setJpush_id(jPushRegId);
					userInfoDao.update(userInfo);
				}
			}

			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(phone);
			userDetailVo.setUserType(userType);// 个人用户
			if (userInfo.getNickname() == null || userInfo.getNickname().isEmpty()) {
				userDetailVo.setNickName(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
			} else {
				userDetailVo.setNickName(userInfo.getNickname());
			}
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setHeadImage(userInfo.getHead_path());
			userDetailVo.setSex(userInfo.getSex().toString());

			resultJsonObject.put("userDetailVo", userDetailVo);

		} else {

			Response response = CodeUtils.getCodeByMainServerCode(status.toString());

			// 如果错误代码是用户不存在
			if (status.toString().equals(MainServerCode.USER_NOT_FOUND)) {

				Map<String, String> regParams = new HashMap<String, String>();

				regParams.put("mobileNo", phone);
				regParams.put("channel", Constants.systemCode);// 渠道号
				regParams.put("merchantCode", Constants.merchantCode);// 所属运营商编码

				// 开始注册
				String regResultString = msrpcService.regist(JSONObject.toJSONString(regParams)).toString();
				JSONObject regResultObject = JSONObject.parseObject(regResultString);
				int opResult = regResultObject.getInteger(Constants.MainServerResultField.OP_RESULT);
				// 判断是否注册成功
				if (opResult == MainOpResult.SUCCESS.getCode()) {

					String userId = regResultObject.getString("userId");
					String token = regResultObject.getString("tocken");

					// 查询app服务器是否含有此用户
					UserInfo userInfo = userInfoDao.findUserByUserId(userId);

					// 如果没有此用户
					if (userInfo == null) {
						// 用户信息
						userInfo = new UserInfo();
						userInfo.setUser_id(userId);
						userInfo.setTelephone(phone);
						userInfo.setLatitude(Float.parseFloat(latitude));
						userInfo.setLongitude(Float.parseFloat(longitude));
						userInfo.setSet_pwd_flag(setPwdFlag.NO.getCode());
						userInfo.setRegister_time(new Date());
						userInfo.setStricted_flag(0);
						userInfo.setKey_char(EncodingUtils.getRandomString(15));
						userInfo.setSet_pwd_flag(setPwdFlag.NO.getCode());
						userInfo.setSex(Sex.MAN.getValue());
						userInfo.setJpush_id(jPushRegId);
						userInfo.setValid_flag(1);
						userInfo.setSysCode(Constants.merchantCode);
						
						List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
						for(UserInfo jpushUser:jpushUsers){
							jpushUser.setJpush_id("");
							//使用这个单条是方便更新缓存
							userInfoDao.update(jpushUser);
						}
						
						// 保存用户信息
						userInfoDao.save(userInfo);
					}

					// 数据拼接
					UserDetailVo userDetailVo = new UserDetailVo();
					userDetailVo.setUserId(userId);
					userDetailVo.setToken(token);
					userDetailVo.setPhone(phone);
					userDetailVo.setUserType(UserType.PERSONAL.getCode());// 个人用户
					if (userInfo.getNickname() == null || userInfo.getNickname().isEmpty()) {
						userDetailVo.setNickName(phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
					} else {
						userDetailVo.setNickName(userInfo.getNickname());
					}
					userDetailVo.setAddress(userInfo.getAddress());
					userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
					userDetailVo.setCarTypeId(userInfo.getCar_type_id());
					userDetailVo.setSignature(userInfo.getSignature());
					userDetailVo.setSex(userInfo.getSex().toString());
					userDetailVo.setHeadImage(userInfo.getHead_path());

					resultJsonObject = JsonUtils.getSuccessJson();
					resultJsonObject.put("userDetailVo", userDetailVo);

				}
				// 注册失败
				else {
					LOG.error(
							"fastLogin is false " + "  phone =" + phone + " registered isfasle  opResult=" + opResult);
					String regErrorCode = regResultObject.getString(Constants.MainServerResultField.ERROR_CODE);
					Response regResponse = CodeUtils.getCodeByMainServerCode(regErrorCode);
					resultJsonObject = JsonUtils.getFailJson(regResponse);
				}
			} else {
				resultJsonObject = JsonUtils.getFailJson(response);
			}
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject updatePassword(String userId, String oldPassword, String newPassword) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("oldPassword", oldPassword);
		params.put("newPassword", newPassword);

		// 修改密码
		String resultJsonString = msrpcService.modifyPwd(JSON.toJSONString(params)).toString();

		LOG.info("MS修改用户ID为【 " + userId + " 】密码返回:" + resultJsonString);

		JSONObject mainServletObject = JSONObject.parseObject(resultJsonString);

		int opResult = mainServletObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			resultJsonObject = JsonUtils.getSuccessJson();

			// 手机号码
			resultJsonObject.put("phone", mainServletObject.getString("mobileNo"));
		} else {
			String errorCode = mainServletObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject resetPassword(String phone, String password, String verifyCode) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobileNo", phone);
		params.put("password", password);
		params.put("checkCode", verifyCode);
		params.put("merchantCode", Constants.merchantCode);
		params.put("type", "1");

		// 修改密码
		String resultJsonString = msrpcService.resetPwd(JSON.toJSONString(params)).toString();

		LOG.info("MS重置手机号码为【 " + phone + " 】密码返回:" + resultJsonString);

		// 转换返回值
		JSONObject mainServletObject = JSONObject.parseObject(resultJsonString);
		int opResult = mainServletObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			resultJsonObject = JsonUtils.getSuccessJson();
		} else {
			String errorCode = mainServletObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject setPassword(String phone, String password, String type, String merchantCode,String userId)
			throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("mobileNo", phone);
		params.put("password", password);
		if (merchantCode == null || merchantCode.trim().equals("")) {
			merchantCode = Constants.merchantCode;
		}
		params.put("merchantCode", merchantCode);
		params.put("type", "0");

		// 修改密码
		String resultJsonString = msrpcService.resetPwd(JSON.toJSONString(params)).toString();

		LOG.info("MS重置手机号码为【 " + phone + " 】密码返回:" + resultJsonString);

		// 转换返回值
		JSONObject mainServletObject = JSONObject.parseObject(resultJsonString);
		int opResult = mainServletObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {
			UserInfo userInfo = userInfoDao.findUserByUserId(userId);
			if(userInfo!=null){
				userInfo.setTelephone(phone);
				userInfo.setSysCode(merchantCode);
				userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
				userInfoDao.update(userInfo);
			}
			
			
			resultJsonObject = JsonUtils.getSuccessJson();
		} else {
			String errorCode = mainServletObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject userExists(String phone) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", phone);
		params.put("merchantCode", Constants.merchantCode);
		params.put("sysCode", Constants.systemCode);// 渠道号

		// 用户是否存在
		String resultJsonString = msrpcService.userIsExists(JSON.toJSONString(params)).toString();

		LOG.info("MS查询此手机号码【 " + phone + " 】是否存在返回:" + resultJsonString);

		// 转换返回值
		JSONObject mainServletObject = JSONObject.parseObject(resultJsonString);
		int opResult = mainServletObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			// 用户是否存在
			String isExists = mainServletObject.getString("isExists");

			if (userIsExists.YES.getCode().equals(isExists)) {
				resultJsonObject = JsonUtils.getSuccessJson();
			} else {
				resultJsonObject = JsonUtils.getFailJson(Response.USER_NOT_FOUND);
			}
		} else {
			String errorCode = mainServletObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject updateUserInfo(String userId, String headPath, String nickName, Integer gender, String addrDetail,
			Float longitude, Float latitude, String email, String signature, String areaCode, String carTypeId)
			throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("nickName", nickName);
		params.put("gender", gender);// 性别
		params.put("addDetail", addrDetail);
		params.put("longitude", longitude);
		params.put("latitude", latitude);
		params.put("email", email);
		params.put("districtCode", areaCode);

		// 调用修改接口
		String resultJsonString = msrpcService.updateUser(JSON.toJSONString(params)).toString();

		LOG.info("MS修改ID为【 " + userId + " 】用户信息返回:" + resultJsonString);

		// 转换返回值
		JSONObject mainServletObject = JSONObject.parseObject(resultJsonString);
		int opResult = mainServletObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			resultJsonObject = JsonUtils.getSuccessJson();

			UserInfo userInfo = new UserInfo();
			userInfo.setUser_id(userId);
			userInfo.setNickname(nickName);
			userInfo.setCar_type_id(carTypeId);
			userInfo.setHead_path(headPath);
			userInfo.setSex(gender);
			userInfo.setAddress(addrDetail);
			userInfo.setLongitude(longitude);
			userInfo.setLatitude(latitude);
			userInfo.setSignature(signature);
			userInfo.setAreaCode(areaCode);
			userInfoDao.update(userInfo);

			// 数据拼接
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setUserType(UserType.PERSONAL.getCode());// 个人用户
			userDetailVo.setNickName(userInfo.getNickname());
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());
			userDetailVo.setAreaCode(areaCode);

			if (!StringUtils.isEmpty(headPath)) {
				userDetailVo.setHeadImage(headPath);
			} else {
				userInfo = userInfoDao.findUserByUserId(userId);
				userDetailVo.setHeadImage(headPath);
			}
			userInfo = userInfoDao.findUserByUserId(userId);
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());

			resultJsonObject.put("userDetailVo", userDetailVo);
		} else {
			String errorCode = mainServletObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject getUserInfoDetail(String userId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", userId);

		// 调用用户详细接口
		String resultJsonString = msrpcService.queryUserDetail(JSON.toJSONString(params)).toString();

		LOG.info("MS获取ID为【 " + userId + " 】用户详细返回:" + resultJsonString);

		// 转换返回值
		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			UserInfo userInfo = userInfoDao.findUserByUserId(userId);
			String token = mainServerResult.getString("tocken");

			// 返回数据
			// 数据拼接
			UserDetailVo userDetailVo = new UserDetailVo();

			// 用户头像
			userDetailVo.setHeadImage(userInfo.getHead_path());
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(userInfo.getTelephone());
			userDetailVo.setUserType(UserType.PERSONAL.getCode());// 个人用户
			userDetailVo.setNickName(userInfo.getNickname());
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setLongitude(userInfo.getLongitude().toString());
			userDetailVo.setLatitude(userInfo.getLatitude().toString());
			userDetailVo.setSex(userInfo.getSex().toString());
			userDetailVo.setAreaCode(userInfo.getAreaCode());

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject getUserCardByUserId(String userId) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);

		// 修改密码
		String resultJsonString = msrpcService.queryCards(JSON.toJSONString(params)).toString();

		LOG.info("MS获取ID【 " + userId + " 】用户卡列表返回:" + resultJsonString);

		JSONObject mainServerObject = JSONObject.parseObject(resultJsonString);

		int opResult = mainServerObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {

			// 手机号码
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());

			// 得到卡列表
			JSONArray cardList = mainServerObject.getJSONArray("cardList");
			// 封装
			resultJsonObject.put("cardList", cardList);
		} else {
			String errorCode = mainServerObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}
		return resultJsonObject;
	}

	public static void main(String args[]) {
//		Object json02 = JSONObject.parse(array.get(i).toString()); 
//		Map<String,Object> jsonmap02 = (Map) json02; 
//		LOG.info("array1.size() = "+array1.size());	
//		String cardNo = jsonmap02.get("cardNo").toString();
//		session.setAttribute(cardNo, userId);
//		session.setAttribute(userId, cardNo);	
//		LOG.info("cardNo + userId:"+ cardNo +" + "+userId);
		
//		Object json02 = JSONObject.parse("{\"cardList\":[{\"cardNo\":\"18808002810000004354\",\"state\":1,\"cardType\":\"08\"}],\"isSuccess\":1}"); 
		Object json02 = JSONObject.parse("{\"cardNo\":\"18808002810000004354\",\"state\":1,\"cardType\":\"08\"}"); 
		Map<String,Object> jsonmap02 = (Map) json02; 
		String cardNo = jsonmap02.get("cardNo").toString();
		System.out.println("cardNo :"+ cardNo );
		
		
		
		
	}
	
	@Override
	public JSONObject getUserWallet(String cardNo) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cardNo", cardNo);

		// 查询用户余额
		String resultJsonString = msrpcService.queryOnlineAccountBal(JSON.toJSONString(params)).toString();

		LOG.info("MS获取卡号为【 " + cardNo + " 】余额返回:" + resultJsonString);

		JSONObject mainResultObject = JSONObject.parseObject(resultJsonString);

		int opResult = mainResultObject.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult == MainOpResult.SUCCESS.getCode()) {
			String balance = mainResultObject.getString("acctBal");
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
			resultJsonObject.put("balance", balance);
		} else {
			String code = mainResultObject.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(code);
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject checkOutToken(String token, String jpushRegId) {

		JSONObject resultJsonObject = new JSONObject();

		ApiResult apiResult = authService.updateToken(token);

		Integer status = apiResult.getStatus();

		// 获取成功
		if (status != null && status == 0) {

			RedisUser redisUser = (RedisUser) apiResult.getData();

			String userId = redisUser.getUserId();
			String resToken = apiResult.getToken();
			UserInfo userInfo = userInfoDao.findUserByUserId(userId);
			if (userInfo != null) {

				// 返回参数
				UserDetailVo userDetailVo = new UserDetailVo();
				userDetailVo.setUserId(userId);
				userDetailVo.setNickName(userInfo.getNickname());
				userDetailVo.setSex(userInfo.getSex().toString());
				userDetailVo.setToken(resToken);
				userDetailVo.setUserType(UserType.PERSONAL.getCode());
				userDetailVo.setAddress(userInfo.getAddress());
				userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
				userDetailVo.setSignature(userInfo.getSignature());
				userDetailVo.setCarTypeId(userInfo.getCar_type_id());
				userDetailVo.setHeadImage(userInfo.getHead_path());
				userDetailVo.setPhone(userInfo.getTelephone());
				resultJsonObject.put("userDetailVo", userDetailVo);
			}

			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());

			// 更新极光推送id
			if(jpushRegId!=null&&(!jpushRegId.equals(""))){
				userInfo.setJpush_id(jpushRegId);
				userInfoDao.update(userInfo);
			}
		} else {
			Response response = CodeUtils.getCodeByMainServerCode(status.toString());
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public String getUserIdByUserCard(String userCard) throws AvroRemoteException {

		// 拼装参数
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("cardNo", userCard);
		params.put("sysCode", Constants.systemCode);
		try {
			String resultJsonString = msrpcService.queryUserIdByCardNo(JSON.toJSONString(params)).toString();

			LOG.info("MS获取卡号为【 " + userCard + " 】的用户ID返回:" + resultJsonString);

			JSONObject mainResultObject = JSONObject.parseObject(resultJsonString);

			int opResult = mainResultObject.getInteger(Constants.MainServerResultField.OP_RESULT);

			if (opResult == MainOpResult.SUCCESS.getCode()) {
				String userId = mainResultObject.getString("userId");
				return userId;
			} else {
				String code = mainResultObject.getString(Constants.MainServerResultField.ERROR_CODE);
				return code;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public JSONObject register(String mobileNo, String systemCode, String merchantCode, String password)
			throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", mobileNo);
		params.put("channel", systemCode);// 渠道号
		params.put("merchantCode", merchantCode);// 所属运营商编码
		params.put("password", password);
		// 调用注册接口
		String resultJsonString = msrpcService.regist(JSON.toJSONString(params)).toString();

		LOG.info("MS注册【 " + mobileNo + " 】号码,返回:" + resultJsonString);

		// 将返回的字符转换成json
		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);

		// 成功
		if (opResult == MainOpResult.SUCCESS.getCode()) {

			String userId = mainServerResult.getString("userId");
			String token = mainServerResult.getString("tocken");

			// 用户信息
			UserInfo userInfo = new UserInfo();
			userInfo.setUser_id(userId);
			userInfo.setTelephone(mobileNo);
			userInfo.setLatitude(Float.parseFloat("0"));
			userInfo.setLongitude(Float.parseFloat("0"));
			userInfo.setAddress("");
			userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
			userInfo.setRegister_time(new Date());
			userInfo.setSex(Sex.MAN.getValue());
			userInfo.setStricted_flag(0);
			userInfo.setKey_char(EncodingUtils.getRandomString(15));
			userInfo.setValid_flag(Valid.YES.getValue());
			userInfo.setSysCode(merchantCode);
			// 保存用户信息
			userInfoDao.save(userInfo);

			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(mobileNo);
			userDetailVo.setUserType(UserType.ENTERPRISE.getCode());// 个人用户
			userDetailVo.setNickName(userInfo.getNickname());
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());

		} else {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response respond = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject.put("code", respond.getCode());
			resultJsonObject.put("msg", respond.getMsg());
		}
		return resultJsonObject;
	}

	public JSONObject register(String mobileNo, String systemCode, String merchantCode, String password, String account,
			String bindingType, String nickname, String sex, String addrDetail, String headPath)
			throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", mobileNo);
		params.put("channel", systemCode);// 渠道号
		params.put("merchantCode", merchantCode);// 所属运营商编码
		params.put("password", password);
		params.put("adddetail", addrDetail);
		params.put("nickname", nickname);
		// 调用注册接口
		String resultJsonString = msrpcService.regist(JSON.toJSONString(params)).toString();

		LOG.info("MS注册【 " + mobileNo + " 】号码,返回:" + resultJsonString);

		// 将返回的字符转换成json
		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);

		// 成功
		if (opResult == MainOpResult.SUCCESS.getCode()) {

			String userId = mainServerResult.getString("userId");
			String token = mainServerResult.getString("tocken");

			// 用户信息
			UserInfo userInfo = new UserInfo();
			userInfo.setUser_id(userId);
			userInfo.setTelephone(mobileNo);
			userInfo.setLatitude(Float.parseFloat("0"));
			userInfo.setLongitude(Float.parseFloat("0"));
			userInfo.setAddress("");
			userInfo.setSet_pwd_flag(setPwdFlag.YES.getCode());
			userInfo.setRegister_time(new Date());
			userInfo.setSex(Sex.MAN.getValue());
			userInfo.setStricted_flag(0);
			userInfo.setKey_char(EncodingUtils.getRandomString(15));
			userInfo.setValid_flag(Valid.YES.getValue());
			userInfo.setSysCode(merchantCode);
			// 保存用户信息
			userInfoDao.save(userInfo);

			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(mobileNo);
			userDetailVo.setUserType(UserType.ENTERPRISE.getCode());// 个人用户
			userDetailVo.setNickName(userInfo.getNickname());
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());

		} else {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response respond = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject.put("code", respond.getCode());
			resultJsonObject.put("msg", respond.getMsg());
		}
		return resultJsonObject;
	}

	public JSONObject autoLogin(String source, String merchantCode, String account, String jPushRegId)
			throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();

		/*
		 * //验证是否存在绑定关系 Map<String,String> params = new
		 * HashMap<String,String>(); //当前固定为1；
		 * if(source.equals(Constants.systemHuatiWeixiCode)){
		 * params.put("bindType", "1"); }else{ //当前没有其他渠道，应该报错
		 * LOG.error("消息请求渠道未授权"); resultJsonObject.put("code",0);
		 * resultJsonObject.put("msg", "不是合法渠道的请求"); return resultJsonObject; }
		 * params.put("thirdUuuid", account); params.put("merchantCode",
		 * merchantCode); params.put("sysCode", source); String
		 * resultJsonString=
		 * msrpcService.existThirdAccountBind(JSON.toJSONString(params)).
		 * toString();
		 * 
		 * LOG.info("用户是否存在绑定关系返回:"+resultJsonString); JSONObject
		 * mainServerResult = JSONObject.parseObject(resultJsonString); //操作结果
		 * int opResult =
		 * mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT
		 * ); if(opResult!=1){ //resultJsonObject=JsonUtils.getSuccessJson();
		 * LOG.error("消息请求渠道未授权"); resultJsonObject.put("code",0);
		 * resultJsonObject.put("msg", "查询用户绑定关系失败"); return resultJsonObject; }
		 * int opResult =
		 * mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT
		 * );
		 */
		// 自动登录
		// 存在然后登录
		LoginParam loginParam = new LoginParam();
		loginParam.setMobileNo(account);
		loginParam.setSysCode(source);
		loginParam.setMerchantCode(merchantCode);
		loginParam.setLoginType(MainServerLoginType.auto.getValue());

		ApiResult apiResult = authService.login(loginParam);

		// 获取返回值
		Integer status = apiResult.getStatus();
		LOG.info(" loginAccount = " + account + " back result:  status= ===============  " + status);
		if (status != null && status == 0) {

			RPCLoginRes loginRes = (RPCLoginRes) apiResult.getData();
			String userId = loginRes.getUserId();
			String token = apiResult.getToken();
			String userType = loginRes.getUserType();

			// 如果账户状态被锁定返回
			int islocked = loginRes.getIsLocked();
			if (islocked == 1) {
				LOG.error("本地数据库用户UserId=" + userId + "被锁定");
				resultJsonObject.put("code", 202);
				resultJsonObject.put("msg", "账户已被锁定，请联系客户");
				return resultJsonObject;
			}
			UserInfo userInfo = userInfoDao.findUserByUserId(userId);
			// 如果App服务器没有此用户
			if (userInfo == null) {
				// 这种情况一般不会发送，提示系统异常
				LOG.error("本地数据库用户UserId=" + userId + "已被删除");
				resultJsonObject.put("code", 0);
				resultJsonObject.put("msg", "本地数据库已不存在该条数据");
				return resultJsonObject;
			}
			// 数据拼接
			// 成功
			UserDetailVo userDetailVo = new UserDetailVo();
			userDetailVo.setUserId(userId);
			userDetailVo.setToken(token);
			userDetailVo.setPhone(userInfo.getTelephone());
			userDetailVo.setUserType(userType);// 个人用户
			if (userInfo.getNickname() == null || userInfo.getNickname().isEmpty()) {
				userDetailVo.setNickName(userInfo.getTelephone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
			} else {
				userDetailVo.setNickName(userInfo.getNickname());
			}
			userDetailVo.setAddress(userInfo.getAddress());
			userDetailVo.setSetPasswordFlag(userInfo.getSet_pwd_flag().toString());
			userDetailVo.setCarTypeId(userInfo.getCar_type_id());
			userDetailVo.setSignature(userInfo.getSignature());
			userDetailVo.setSex(userInfo.getSex().toString());
			userDetailVo.setHeadImage(userInfo.getHead_path());
			userDetailVo.setAreaCode(userInfo.getAreaCode());

			// 如果是电桩用户更新jpushID
			if (source.equals(Constants.systemCode)) {
				
				List<UserInfo> jpushUsers=getUsersByJpush(jPushRegId) ;
				for(UserInfo jpushUser:jpushUsers){
					jpushUser.setJpush_id("");
					//使用这个单条是方便更新缓存
					if(jpushUser.getUser_id().equals(userInfo.getUser_id())){
						continue;
					}
					userInfoDao.update(jpushUser);
				}
				
				userInfo.setJpush_id(jPushRegId);
				userInfoDao.update(userInfo);
			}

			resultJsonObject.put("userDetailVo", userDetailVo);
			resultJsonObject.put("code", Response.SUCCESS.getCode());
			resultJsonObject.put("msg", Response.SUCCESS.getMsg());
		} else {
			LOG.error("login RpcServers is false ");
			Response response = CodeUtils.getCodeByMainServerCode(status.toString());
			resultJsonObject.put("code", response.getCode());
			resultJsonObject.put("msg", response.getMsg());
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject unlockUser(String source, String merchantCode, String account, String jPushRegId, String bindType)
			throws AvroRemoteException {
		LOG.info("解绑用户传入参数source=" + source + ";merchantcode=" + merchantCode + "account=" + account + ";jpushRegId="
				+ jPushRegId + ";bindType=" + bindType);
		JSONObject resultJsonObject = new JSONObject();

		// 查询是否绑定；
		Map<String, String> params = new HashMap<String, String>();
		params.put("tokenKey", account);

		// 当前固定为1；
		if (ConverUtil.checkDataSource(source, merchantCode) == 1
				|| ConverUtil.checkDataSource(source, merchantCode) == 2) {
			//不传绑定方式默认解绑微信
			if (bindType == null || bindType.trim().equals("")) {
				bindType = ConverUtil.weixinSource;
			}
			params.put("bindType", bindType);
		} else {
			// 当前没有其他渠道，应该报错
			LOG.error("消息请求渠道未授权");
			resultJsonObject.put("code", 0);
			resultJsonObject.put("msg", "不是合法渠道的请求");
			return resultJsonObject;
		}
		// params.put("thirdUuuid", jPushRegId);
		params.put("merchantCode", merchantCode);
		params.put("sysCode", source);

		String resultJsonString = msrpcService.offBindThirdAccount(JSON.toJSONString(params)).toString();

		LOG.info("MS解绑用户:" + resultJsonString);

		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		// 操作结果
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		if (opResult == 1) {
			resultJsonObject = JsonUtils.getSuccessJson();
		} else {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			if (errorCode.equals(MainServerCode.NOT_EXITS)) {
				resultJsonObject = JsonUtils.getSuccessJson();
			}
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	@Override
	public JSONObject getWeixinDetail(String openid, String access_token) throws AvroRemoteException {

		JSONObject resultJsonObject = new JSONObject();
		Map<String, String> params = new HashMap<String, String>();
		params.put("openid", openid);
		params.put("access_token", access_token);
		// 主服务的地址已发生变化
		String entitys = HttpUtils.getRequest(Constants.weixinUrl.WEIXIN_USERINFO, params);
		JSONObject userInfoResult = JSONObject.parseObject(entitys);
		// 用户请求返回的数据
		LOG.info(entitys);
		String errcode = userInfoResult.getString("errcode");
		// 如果没有错误代码，所以返回成功
		if (errcode == null) {
			resultJsonObject = JsonUtils.getSuccessJson();
			JSONObject data = new JSONObject();
			data.put("subscribe", userInfoResult.getString("subscribe"));
			data.put("nickname", userInfoResult.getString("nickname"));
			data.put("openid", userInfoResult.getString("openid"));
			resultJsonObject.put("data", data);
		} else {
			LOG.error("消息请求渠道未授权");
			resultJsonObject.put("code", 0);
			resultJsonObject.put("msg", "不是合法渠道的请求");
		}
		return resultJsonObject;
	}

//	public static void main(String[] args) {
//		UserInfoServiceImpl userimpl = new UserInfoServiceImpl();
//		// userimpl.userLogin("", "15400000001", "123456", "");
//		try {
//			userimpl.getWeixinDetail("1", "YrUhWMy3qjLp0tZ0fq8wA4SF3ptKRdnQ28e_5nUR4aAew8RW");
//		} catch (AvroRemoteException e) {
//			e.printStackTrace();
//		}
//
//	}

	@Override
	public JSONObject bindShipList(String phone, String bindType, String source, String merchantCode)
			throws AvroRemoteException {
		LOG.info("查询帐号【" + phone + "】的绑定关系为【" + bindType + "】运营商编号为【" + merchantCode + "】");
		Map<String, String> params = new HashMap<String, String>();
		params.put("tokenKey", phone);
		if(bindType!=null&&bindType.length()>0)
		params.put("bindType", bindType);
		if (source == null || StringUtils.isEmpty(source)) {
			source = Constants.systemCode;
		}
		params.put("sysCode", source);
		if ((merchantCode == null) || (StringUtils.isEmpty(merchantCode))) {
			merchantCode = Constants.merchantCode;	
		}
		params.put("merchantCode", merchantCode);
		String resultJsonString = msrpcService.queryBindThirdAccount(JSON.toJSONString(params)).toString();
		LOG.info("查询绑定关系返回的结果是：" + resultJsonString);
		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		// 操作结果
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		JSONObject resultJsonObject = new JSONObject();
		if (opResult == 1) {
			resultJsonObject = JsonUtils.getSuccessJson();
			resultJsonObject.put("data", mainServerResult.get(Constants.MainServerResultField.RESULT));
		} else {
			LOG.info("查询绑定列表返回错误消息"+ mainServerResult.getString("msg"));
			resultJsonObject.put("code", 200);
			resultJsonObject.put("msg", mainServerResult.getString("msg"));
		}

		return resultJsonObject;
	}

	@Override
	public JSONObject bindingUser(String phone, String verifyCode, String source, String merchantCode, String account,
			String bindingType, String nickname, String sex, String addrDetail, String headPath)
			throws AvroRemoteException {

		LOG.info("绑定手机号传入参数source=" + source + "merchantCode=" + merchantCode + "account=" + account + "bindingType="
				+ bindingType + "'");
		JSONObject resultJsonObject = new JSONObject();
		// 拼装参数
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", phone);
		params.put("checkCode", verifyCode);
		// 发送验证码
		String resultJsonString = msrpcService.verifyCheckCode(JSON.toJSONString(params)).toString();

		LOG.info("MS验证码校验返回:" + resultJsonString);

		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);

		// 验证码返回结果 1 成功
		int opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);

		if (opResult != 1) {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			return resultJsonObject = JsonUtils.getFailJson(response);
		}
		// 验证用户存在
		resultJsonString = userIsExist(phone, merchantCode, source);
		mainServerResult = JSONObject.parseObject(resultJsonString);
		opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		String isExists = mainServerResult.getString("isExists");
		LOG.info("验证用户是否存在返回结果：【" + resultJsonString + "】");
		// 验证用户失败
		if (opResult != 1) {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			return resultJsonObject = JsonUtils.getFailJson(response);
		}
		// 用户不存在
		if (userIsExists.NO.getCode().equals(isExists)) {
			// 用户不存在
			// 调用注册接口
			mainServerResult = register(phone, source, merchantCode, verifyCode, account, bindingType, nickname, sex,
					addrDetail, headPath);
			LOG.info("注册存在返回结果：【" + resultJsonString + "】");
			// 注册失败，调用绑定接口
			if (!mainServerResult.getString("code").equals(Response.SUCCESS.getCode())) {
				String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
				Response response = CodeUtils.getCodeByMainServerCode(errorCode);
				return resultJsonObject = JsonUtils.getFailJson(response);
			}
		} else {
			// 用户存在，在验证存在绑定关系
			
			
			Map<String, String> bindParams = new HashMap<String, String>();
			bindParams.put("bindType", bindingType);
			bindParams.put("thirdUuuid", account);
			bindParams.put("merchantCode", merchantCode);
			bindParams.put("sysCode", source);
			resultJsonString = msrpcService.existThirdAccountBind(JSON.toJSONString(bindParams)).toString();
			LOG.info("获取绑定关系接口：【" + resultJsonString + "】");
			mainServerResult = JSONObject.parseObject(resultJsonString);
			opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
			if (opResult != 1) {
				String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
				Response response = CodeUtils.getCodeByMainServerCode(errorCode);
				return resultJsonObject = JsonUtils.getFailJson(response);
			}
			Integer isExist = mainServerResult.getInteger("isExist");
			LOG.info("验证绑定关系isExist=" + isExist + ";");///
			
			
			
			if (isExist == null || isExist == 1) {
				// 提示已存在绑定关系
				Response response = Response.REPEAT_IS_BIND;
				return resultJsonObject = JsonUtils.getFailJson(response);
			}
		}
		// 绑定用户
		resultJsonString = bindThirdAccount(phone, source, account, merchantCode, bindingType);
		mainServerResult = JSONObject.parseObject(resultJsonString);
		opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		// 绑定成功，调用登录接口
		LOG.info("用户绑定结果：" + resultJsonString);
		if (opResult == 1) {
			return resultJsonObject = JsonUtils.getSuccessJson();
		} else {
			// 绑定失败
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;
	}

	/**
	 * 判断用户是否存在
	 * 
	 * @param phone
	 *            手机号
	 * @param merchantCode
	 *            运营商
	 * @param source
	 *            系统码，渠道
	 * @return
	 * @throws AvroRemoteException
	 */
	private String userIsExist(String phone, String merchantCode, String source) throws AvroRemoteException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("mobileNo", phone);
		params.put("merchantCode", merchantCode);
		params.put("sysCode", source);
		return msrpcService.userIsExists(JSON.toJSONString(params)).toString();
	}

	private String bindThirdAccount(String phone, String source, String account, String merchantCode,
			String bindingType) throws AvroRemoteException {
		Map<String, String> params = new HashMap<String, String>();
		params.put("tokenKey", phone);
		params.put("thirdUuuid", account);
		params.put("merchantCode", merchantCode);
		params.put("sysCode", source);
		//返回1 华体 返回2电桩
		if (ConverUtil.checkDataSource(source, merchantCode) == 1
				|| ConverUtil.checkDataSource(source, merchantCode) == 2) {
			if (bindingType.equals("")) {
				bindingType = "1";
			}
			params.put("bindType", bindingType);
		} else {
			// 如果没有匹配上，绑定失败
			LOG.error("系统编码=" + source + "错误");
			JSONObject resultJsonObject = new JSONObject();
			resultJsonObject.put("isSuccess", 0);
			resultJsonObject.put("errorMsg", "系统编号错误");
			resultJsonObject.put("errorCode", "");
			return resultJsonObject.toJSONString();
		}
		return msrpcService.bindThirdAccount(JSON.toJSONString(params)).toString();
	}

	@Override
	public JSONObject loginBindingUser(String phone, String userId, String account, String bindingType, String source,
			String merchantCode) throws AvroRemoteException {
		// TODO Auto-generated method stub
		LOG.info("绑定手机号传入参数phone=" + phone + "userId=" + userId + "account=" + account + "bindingType=" + bindingType);
		LOG.info("绑定手机号传入参数source=" + source + "merchantCode=" + merchantCode);

		JSONObject resultJsonObject = new JSONObject();

		// 用户存在，在验证存在绑定关系
		Map<String, String> bindParams = new HashMap<String, String>();
		bindParams.put("bindType", bindingType);
		bindParams.put("thirdUuuid", account);
		bindParams.put("merchantCode", merchantCode);
		bindParams.put("sysCode", source);
		String resultJsonString = msrpcService.existThirdAccountBind(JSON.toJSONString(bindParams)).toString();

		LOG.info("获取绑定关系接口：【" + resultJsonString + "】");

		JSONObject mainServerResult = JSONObject.parseObject(resultJsonString);
		Integer opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		if (opResult != 1) {
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			return resultJsonObject = JsonUtils.getFailJson(response);
		}

		Integer isExist = mainServerResult.getInteger("isExist");
		LOG.info("验证绑定关系isExist=" + isExist + ";");
		if (isExist == null || isExist == 1) {
			// 提示已存在绑定关系
			Response response = Response.REPEAT_IS_BIND;
			return resultJsonObject = JsonUtils.getFailJson(response);
		}

		// 绑定用户
		resultJsonString = bindThirdAccount(phone, source, account, merchantCode, bindingType);
		mainServerResult = JSONObject.parseObject(resultJsonString);
		opResult = mainServerResult.getInteger(Constants.MainServerResultField.OP_RESULT);
		// 绑定成功，调用登录接口
		LOG.info("用户绑定结果：" + resultJsonString);
		if (opResult == 1) {
			return resultJsonObject = JsonUtils.getSuccessJson();
		} else {
			// 绑定失败
			String errorCode = mainServerResult.getString(Constants.MainServerResultField.ERROR_CODE);
			Response response = CodeUtils.getCodeByMainServerCode(errorCode);
			resultJsonObject = JsonUtils.getFailJson(response);
		}
		return resultJsonObject;

	}
	
	public List<UserInfo> getUsersByJpush(String jPushId){
		UserInfo userInfo= new UserInfo();
		userInfo.setJpush_id(jPushId);
	    List<UserInfo>	userInfos=userInfoDao.getAllUsers(userInfo);
	    return userInfos;
		
	}

}